package com.lanou.musicproject.activity;


import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.lanou.musicproject.R;
import com.lanou.musicproject.ResideMenu.ResideMenu;
import com.lanou.musicproject.ResideMenu.ResideMenuItem;
import com.lanou.musicproject.base.BaseApplication;
import com.lanou.musicproject.bean.MyMusicList;
import com.lanou.musicproject.bean.MySong;
import com.lanou.musicproject.event.MyEvent;
import com.lanou.musicproject.fragment.HomePageFragment;
import com.lanou.musicproject.fragment.LeftFragment;
import com.lanou.musicproject.fragment.MyFragment;
import com.lanou.musicproject.fragment.RecommFragment;
import com.lanou.musicproject.fragment.RightFragment;
import com.lanou.musicproject.manager.SkinSettingManager;
import com.lanou.musicproject.musicservice.MusicInterface;
import com.lanou.musicproject.musicservice.MusicService;
import com.lanou.musicproject.suspendservice.FxService;
import com.lanou.musicproject.tools.Time;
import com.lanou.musicproject.utils.MyConfig;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity implements
        LeftFragment.ToRightFragment, View.OnClickListener,
        ResideMenu.OnMenuListener, RecommFragment.IntentListener, SensorEventListener {

    private SkinSettingManager mSkinSettingManager;
    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";

    private static MusicInterface mi;
    private static SeekBar sb;
    private MyServiceConn conn;
    private Intent intent;
    private static ImageView mini_play, popupWindow;
    private static TextView playerSongName;
    private static TextView playerSingerName;
    private static CircleImageView player_singer_image;
    private static Context mContext;
    private static TextView start_time, end_time;
    @Bind(R.id.mini_next)
    ImageView mini_next;
    private TabHost mTabHost;

    private ImageView seek_image;
    private ResideMenu resideMenu;

    private ResideMenuItem itemLogin, itemDownload, itemBackground, itemFloat, itemQuit;

    private FragmentManager manager;
    private LinearLayout LLminiplayer;
    private SensorManager sensorManager;

    private int mScreenWidth;

    public static int PLAYMODE;

    public static final int PLAYLOCAL = 0;
    public static final int PLAYONLINE = 1;

    public static final int RANDOM = 2;
    public static final int INORDER = 3;
    public static final int SINGLE = 4;

    public static int REPEATMODE = INORDER;

    private long mExitTime;
    private int[] skinResources = {R.mipmap.a0, R.mipmap.a1, R.mipmap.ping, R.mipmap.a3, R.mipmap.a4, R.mipmap.hua
            , R.mipmap.jing, R.mipmap.a7, R.mipmap.pei, R.mipmap.a9};
    private int state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //配置个推
        PushManager.getInstance().initialize(this.getApplicationContext());

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        mContext = this;
        ButterKnife.bind(this);
        LLminiplayer = (LinearLayout) findViewById(R.id.LLminiplayer);
        sb = (SeekBar) findViewById(R.id.sb);
        start_time = (TextView) findViewById(R.id.start_time);
        end_time = (TextView) findViewById(R.id.end_time);
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //根据拖动的进度改变音乐播放进度
                int progress = seekBar.getProgress();
                //改变播放进度
                mi.seekTo(progress);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
            }
        });
        mini_play = (ImageView) findViewById(R.id.mini_play);
        playerSingerName = (TextView) findViewById(R.id.player_singer_name);
        playerSongName = (TextView) findViewById(R.id.player_song_name);
        player_singer_image = (CircleImageView) findViewById(R.id.player_singer_image);

        intent = new Intent(this, MusicService.class);
        startService(intent);
        conn = new MyServiceConn();
        bindService(intent, conn, BIND_AUTO_CREATE);


        initTab();
        initResideMenu();

        LLminiplayer.setOnClickListener(this);
        mini_play.setOnClickListener(this);
        mini_next.setOnClickListener(this);

        //获取屏幕尺寸
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;

        //注册一个广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ALARM_CLOCK_BROADCAST);
        registerReceiver(mAlarmReceiver, filter);

        EventBus.getDefault().register(this);
    }


    @Override
    protected void onResume() {
        super.onResume();

        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        sensorManager.unregisterListener(this);
    }

    public void onEvent(MyEvent.PlayEvent playEvent) {
        switch (playEvent.getWhat()) {
            case PLAYLOCAL:
                PLAYMODE = PLAYLOCAL;
                Log.i("--mainplaymode--", PLAYLOCAL + "");
                break;
            case PLAYONLINE:
                PLAYMODE = PLAYONLINE;
                Log.i("--mainplaymode--", PLAYONLINE + "");
                break;
            case RANDOM:
                REPEATMODE = RANDOM;
                Log.i("--mainrepeatmode--", RANDOM + "");
                break;
            case INORDER:
                REPEATMODE = INORDER;
                Log.i("--mainrepeatmode--", INORDER + "");
                break;
            case SINGLE:
                REPEATMODE = SINGLE;
                Log.i("--mainrepeatmode--", SINGLE + "");
                break;
        }
    }


    //接收换肤的状态回调
    public void onEvent(MyEvent.ChangeSkin event) {
        state = event.getStateNum();
        resideMenu.setBackground(skinResources[state]);
        Log.i("xxx", "设置数据成功");
    }

    private void initResideMenu() {
        resideMenu = new ResideMenu(this);
//        resideMenu.setBackground(R.mipmap.ba);
        SharedPreferences sharedPreferences = getSharedPreferences("wangshimei", MODE_PRIVATE);
        state = sharedPreferences.getInt("count", 0);
        resideMenu.setBackground(skinResources[state]);
        resideMenu.attachToActivity(this);


        itemBackground = new ResideMenuItem(this, R.mipmap.img_choose_photo_for_background, "换背景");
        itemDownload = new ResideMenuItem(this, R.mipmap.bt_sceneplay_down_press, "下载管理");
        itemFloat = new ResideMenuItem(this, R.mipmap.ktv_share_icon_plan, "浮动窗口启动");
        itemLogin = new ResideMenuItem(this, R.mipmap.ktv_result_img_light, "登录");
        itemFloat = new ResideMenuItem(this, R.mipmap.img_background_imageview_soundsearch_center, "浮动窗口启动");
        itemQuit = new ResideMenuItem(this, R.mipmap.ic_list_dropdown_sleep_press, "定时关闭");


        resideMenu.addMenuItem(itemDownload);
        resideMenu.addMenuItem(itemFloat);
        resideMenu.addMenuItem(itemBackground);
        resideMenu.addMenuItem(itemLogin);
        resideMenu.addMenuItem(itemQuit);


        itemLogin.setOnClickListener(this);
        itemDownload.setOnClickListener(this);
        itemBackground.setOnClickListener(this);
        itemFloat.setOnClickListener(this);
        itemQuit.setOnClickListener(this);

        resideMenu.setScaleValue(0.6f);
        resideMenu.setMenuListener(this);
        resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
    }


    @Override
    public void onClick(View v) {

        if (v == itemLogin) {
            Log.i("----reside----", "login");
            Intent intentLogin = new Intent(this, LoginActivity.class);
            startActivity(intentLogin);
        } else if (v == itemDownload) {
            Intent intentDown = new Intent(this, DownloadManagerActivity.class);
            startActivity(intentDown);
        } else if (v == itemFloat) {
            Intent intentstart = new Intent(MainActivity.this, FxService.class);
            startService(intentstart);
        } else if (v.getId() == R.id.LLminiplayer) {
            //点击mini播放器 跳转至完整播放器
            Intent intent = new Intent(this, MusicPlayActivity.class);
            startActivity(intent);

        } else if (v.getId() == R.id.mini_play) {
            if (mi.getIsPlay()) {
                mi.pause();
            } else if (mi.getDuration() > mi.getProgress()) {
                mi.continuePlay();
            }

        } else if (v.getId() == R.id.mini_next) {

            if (PLAYMODE == PLAYONLINE) {
                mi.next();
            } else if (PLAYMODE == PLAYLOCAL) {
                mi.localNext();
            }

        } else if (v == itemBackground) {
            Intent intentBackground = new Intent(this, SkinInnerActivity.class);
            startActivity(intentBackground);
        } else if (v == itemQuit) {

            showDialog();
        }

    }


    public void showDialog() {
        View dialogView = View.inflate(MainActivity.this, R.layout.sleep_time, null);
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (mScreenWidth * 0.8);
        dialogWindow.setAttributes(lp);
        dialogWindow.setTitle("定时关闭");
        dialog.show();


        final Button cancleBtn = (Button) dialogView.findViewById(R.id.cancle_btn);
        final Button okBtn = (Button) dialogView.findViewById(R.id.ok_btn);
        final EditText timeEt = (EditText) dialogView.findViewById(R.id.time_et);
        View.OnClickListener listener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == cancleBtn) {
                    dialog.dismiss();
                    Toast.makeText(mContext, "您取消了定时关闭", Toast.LENGTH_SHORT).show();
                } else if (v == okBtn) {
                    String timeS = timeEt.getText().toString();
                    if (TextUtils.isEmpty(timeS)
                            || Integer.parseInt(timeS) == 0) {
                        Toast.makeText(getApplicationContext(), "输入无效！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setSleepClock(timeS);
                    dialog.dismiss();
                }
            }
        };

        cancleBtn.setOnClickListener(listener);
        okBtn.setOnClickListener(listener);
    }

    /**
     * 设置睡眠闹钟
     */
    private void setSleepClock(String timeS) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(timeS);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        BaseApplication.mIsSleepClockSetting = true;
        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后退出软件", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 取消睡眠闹钟
     */
    private void cancleSleepClock() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pendingIntent);
        BaseApplication.mIsSleepClockSetting = false;
    }


    private void initTab() {

        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();
        initView();
        TabHost.TabSpec tab2 = mTabHost.newTabSpec("tab2");
        View view2 = getLayoutInflater().inflate(R.layout.tabs_person, null);
        tab2.setIndicator(view2);
        tab2.setContent(R.id.tabcontent_view2);
        mTabHost.addTab(tab2);
        // 标签2
        TabHost.TabSpec tab3 = mTabHost.newTabSpec("tab3");
        View view3 = getLayoutInflater().inflate(R.layout.tabs_recommend, null);
        tab3.setIndicator(view3);
        tab3.setContent(R.id.tabcontent_view3);
        mTabHost.addTab(tab3);
        // 标签3
        TabHost.TabSpec tab4 = mTabHost.newTabSpec("tab4");
        View view4 = getLayoutInflater().inflate(R.layout.tabs_music, null);
        tab4.setIndicator(view4);
        tab4.setContent(R.id.tabcontent_view4);
        mTabHost.addTab(tab4);

        mTabHost.setCurrentTab(0);
        manager = getSupportFragmentManager();
        FragmentTransaction t = manager.beginTransaction();
        t.replace(R.id.tabcontent_view2, new MyFragment());
        t.replace(R.id.tabcontent_view3, new RecommFragment());
        t.replace(R.id.tabcontent_view4, new HomePageFragment(), "musicfragment");
        t.commit();

    }

    private void initView() {
        //跳转到搜索页面
        seek_image = (ImageView) findViewById(R.id.seek_image);
        seek_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SeekActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void openMenu() {
    }

    @Override
    public void closeMenu() {
    }

    @Override
    public void onToRightListener(int index) {
        //LeftFragment跳转RightFragment
        HomePageFragment musicFragment = (HomePageFragment) manager.findFragmentByTag("musicfragment");

        RightFragment rightFragment = (RightFragment) musicFragment.getFragmentManager().findFragmentByTag("right");
        ViewPager viewPager = rightFragment.getViewPager();
        switch (index) {
            case 0:
                viewPager.setCurrentItem(0);
                break;
            case 1:
                viewPager.setCurrentItem(1);
                break;
            case 2:
                viewPager.setCurrentItem(2);
                break;
            case 3:
                viewPager.setCurrentItem(3);
                break;
            case 4:
                viewPager.setCurrentItem(4);
                break;
            case 5:
                viewPager.setCurrentItem(5);
                break;
            case 6:
                viewPager.setCurrentItem(6);
                break;
            case 7:
                viewPager.setCurrentItem(7);
                break;
            case 8:
                viewPager.setCurrentItem(8);
                break;
            case 9:
                viewPager.setCurrentItem(9);
                break;
            default:
                break;
        }


    }

    public void onListener(String str) {

        mTabHost.setCurrentTab(2);
        HomePageFragment musicFragment = (HomePageFragment) manager.findFragmentByTag("musicfragment");

        ViewPager viewlistPager = musicFragment.getViewPager();

        switch (str) {
            case "songlist":
                viewlistPager.setCurrentItem(2);
                break;
        }


    }

    /**
     * 传感器变化调用的方法
     */
    @Override
    public void onSensorChanged(SensorEvent event) {

        int sensorType = event.sensor.getType();

        float[] values = event.values;

        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math
                    .abs(values[2]) > 17)) {
                if (PLAYMODE == PLAYONLINE) {
                    mi.next();
                } else if (PLAYMODE == PLAYLOCAL) {
                    mi.localNext();
                }
            }
        }
    }

    /**
     * 传感器精度改变的回调方法
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }

    }

    public static Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            int currentPostition = bundle.getInt("currentPosition");
            //刷新进度条的进度
            sb.setMax(duration);
            sb.setProgress(currentPostition);
            start_time.setText(Time.formatTime((long) currentPostition));
            end_time.setText(Time.formatTime((long) duration));
            init();

        }
    };

    //设置图片样式
    private static void init() {
        if (mi.getIsPlay()) {
            mini_play.setImageResource(R.mipmap.player_btn_pause);
        } else {
            mini_play.setImageResource(R.mipmap.player_btn_play);
        }
        playerSongName.setText(mi.getName());
        playerSingerName.setText(mi.getSinger());
        Picasso.with(mContext).load(mi.getPlayer_Singer_Image()).into(player_singer_image);

//        Log.i("--bitmap--", mi.getPlayer_Singer_Image());
        /**
         *
         * mi.getPlayer_Singer_Image()是图片url
         *
         * 转成bitmap
         *
         * 获取有活力的颜色传入播放器背景
         *
         *
         * */

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                if (mi.getPlayer_Singer_Image() != null) {

                    Bitmap albumBmp = returnBitmap(mi.getPlayer_Singer_Image());

                    if (albumBmp != null) {

                        Palette palette = Palette.from(albumBmp).generate();

                        Palette.Swatch swatch = palette.getVibrantSwatch();

                        if (swatch != null) {
                            int rgb = swatch.getRgb();
                            /**
                             *
                             * 发个广播
                             *
                             * */
                            Intent intent = new Intent();
                            intent.putExtra("rgb", rgb);
                            intent.setAction("rgbAction");
                            mContext.sendBroadcast(intent);

                        }
                    }
                    // 先判断是否已经回收
                    if (albumBmp != null && !albumBmp.isRecycled()) {
                        // 回收并且置为null
                        albumBmp.recycle();
                        albumBmp = null;
                    }
                }
            }
        });
        thread.start();

        System.gc();

    }


    public static Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    public static void mini_play(ArrayList<MyMusicList> lists, int position) {


        PLAYMODE = PLAYONLINE;
        if (mi != null) {
            mi.play(lists, position);
        }

    }

    public static void mini_play(List<MySong> mysong, int position) {

        PLAYMODE = PLAYLOCAL;

        if (mi != null)
            mi.playLocal(mysong, position);
    }


    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //退出程序
            finish();
        }

    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        EventBus.getDefault().unregister(this);
        SharedPreferences sharedPreferences = getSharedPreferences("wangshimei", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("count", state);
        editor.commit();
        editor.clear();

        cancleSleepClock();
        System.exit(0);
    }


    // 对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出施美音乐", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MyConfig.clearSharePre(this, "user");
                MyConfig.clearSharePre(this, "img");
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
